vector的reserve的使用(避免内存重新分配以及内存分配的方式) |
您所在的位置:网站首页 › reserve wine什么意思 › vector的reserve的使用(避免内存重新分配以及内存分配的方式) |
文章目录
vector的reserve的作用Demo:对比使用reserve的区别Demo运行结果分析新的疑问:大于capacity指定之后的动态分配重新分配空间后内存地址的变化
vector的reserve的作用
之前提到vector中不断的push_back,会进行内存的重新自动分配的问题 (详见:https://blog.csdn.net/hl_zzl/article/details/84798804 ) 为了避免重新分配内存带来的问题,vector提供了reserve函数。 std::vector::reserve void reserve (size_type n);Request a change in capacity Requests that the vector capacity be at least enough to contain n elements. If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater). In all other cases, the function call does not cause a reallocation and the vector capacity is not affected. This function has no effect on the vector size and cannot alter its elements. reserve的作用是更改vector的容量(capacity),使vector至少可以容纳n个元素。 如果n大于vector当前的容量,reserve会对vector进行扩容。其他情况下都不会重新分配vector的存储空间 Demo:对比使用reserve的区别说明:在main中声明了两个vector,vecInt为默认初始化,vecIntB使用capacity初始化其容量为100。分别对vetIntA和vecIntB进行同样的操作: ①把0~99依次push_back到vector中, ②在push_back的过程中观察vector的容量capacity是否发生变化。 #include #include #include using namespace std; void growPushBack(vector &vec, uint16_t size){ for(int i = 0; i |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |